<?php

namespace SmmsSdk\Core;

use Hanson\Foundation\AbstractAPI;
use Psr\Http\Message\ResponseInterface;
use SmmsSdk\Application;
use SmmsSdk\Auth\AccessToken;

class Api extends AbstractAPI
{
    /**
     * @return Application $app
     */
    protected $app;

    /**
     * @var AccessToken
     */
    public $accessToken;

    /**
     * @param $app
     */
    public function __construct(Application $app, AccessToken $accessToken)
    {
        $this->app = $app;
        $this->accessToken = $accessToken;
    }

    public function request(string $method, string $url, array $params, array $headers = [], $files = [])
    {
        $http = $this->getHttp();

        $headers = array_merge($headers, [
            'Authorization' => $this->accessToken->getToken() ?: ''
        ]);

        $http->addMiddleware($this->headerMiddleware($headers));

        /** @var ResponseInterface $response */
        $response = call_user_func_array([$http, $method], [$this->app->getConfig('base_url') . $url, $params, $files]);

        $result = json_decode(strval($response->getBody()), true);

        $this->checkErrorAndThrow($result);

        return $result;
    }


    protected function checkErrorAndThrow($result)
    {
        if (!$result || !$result['success']) {
            throw new \Exception($result['message']);
        }
    }


}